<?php
namespace App\Services;

use App\Exceptions\WechatException;
use GuzzleHttp\Client;
use Illuminate\Support\Facades\Cache;

class MiniAppService
{
    protected $appid;

    protected $secret;

    public function __construct($appid, $secret)
    {
        $this->appid = $appid;
        $this->secret = $secret;
    }

    /**
     * 获取access_oken
     * @return string
     */
    public function getAccessToken()
    {
        return Cache::remember('access_token:' . $this->appid, 7000, function () {
            $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=' . $this->appid . '&secret=' . $this->secret;
            $client = new Client();
            $result = $client->get($url)->getBody();
            $resultArr = json_decode($result, true);
            if (empty($resultArr['access_token'])) {
                throw new WechatException('get access_token error. code:' . $resultArr['errcode'] . ' msg:' . $resultArr['errmsg']);
            }
            return $resultArr['access_token'];
        });
    }

    /**
     * @param $code
     * @return mixed
     * @throws WechatException
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function code2Session($code)
    {
        $url = 'https://api.weixin.qq.com/sns/jscode2session?appid=' . $this->appid . '&secret=' . $this->secret . '&js_code=' . $code . '&grant_type=authorization_code';
        $client = new Client();
        $response = $client->get($url)->getBody()->getContents();
        $resultArr = json_decode($response, true);
        if (isset($resultArr['openid'])) {
            return $resultArr;
        }
        throw new WechatException('获取用户openid失败  :mini');
    }

    /**
     * 获取url scheme
     * @param $path
     * @param $query
     * @param bool $isExpire
     * @param null $expireTime
     * @return mixed
     * @throws WechatException
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function getUrlScheme($path, $query, $isExpire = true, $expireTime = null)
    {
        if (is_null($expireTime)) {
            $expireTime = time() + 300;
        }
        $url = 'https://api.weixin.qq.com/wxa/generatescheme?access_token=' . $this->getAccessToken();
        $client = new Client();
        $response = $client->post($url, [
            'json' => [
                'jump_wxa' => [
                    'path' => $path,
                    'query' => $query
                ],
                'is_expire' => $isExpire,
                'expire_time' => $expireTime
            ]
        ])->getBody()->getContents();
        $resultArr = json_decode($response, true);
        if (0 === (int)$resultArr['errcode']) {
            return $resultArr['openlink'];
        }
        throw new WechatException('获取失败 ： ' . $resultArr['errmsg'] . ' code：' . $resultArr['errcode']);
    }

    public function getQrcode()
    {

    }
}
